<!--
 * @Author: anxia.ack anchenkai@come-future.com
 * @Date: 2025-04-20 14:24:10
 * @LastEditors: anxia.ack anchenkai@come-future.com
 * @LastEditTime: 2025-05-07 22:12:13
 * @FilePath: /free-learning-front/src/views/MyVReviewView.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="my-review">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="课程评价" name="course">
        <!-- 查询条件 -->
        <div class="query-form">
          <el-form :model="queryForm" inline>
            <el-form-item label="课程">
              <el-select
                v-model="queryForm.courseId"
                placeholder="请选择课程"
                clearable
                filterable
              >
                <el-option
                  v-for="course in courseList"
                  :key="course.id"
                  :label="course.title"
                  :value="course.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="queryForm.status"
                placeholder="请选择状态"
                clearable
              >
                <el-option label="审核中" :value="0" />
                <el-option label="已通过" :value="1" />
                <el-option label="已拒绝" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="关键字">
              <el-input
                @keyup.enter="handleQuery"
                v-model="queryForm.keyword"
                placeholder="请输入评论内容关键字"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 评论列表 -->
        <div class="review-list">
          <el-empty v-if="reviewList.length === 0" description="暂无评论" />
          <template v-else>
            <div v-for="item in reviewList" :key="item.id" class="review-item">
              <div class="review-header">
                <div class="course-info">
                  <el-avatar :src="item.avatar" />
                  <div class="info">
                    <div class="course-name">{{ item.courseName }}</div>
                    <div class="review-time">{{ formatTime(item.reviewTime) }}</div>
                  </div>
                </div>
                <div
                  class="review-status"
                  style="display: flex; align-items: center"
                >
                  <el-tooltip
                    v-if="item.status === 2"
                    :content="'拒绝原因:' + item.auditInfo"
                    placement="top"
                  >
                    <el-icon style="margin-right: 10px">
                      <InfoFilled />
                    </el-icon>
                  </el-tooltip>
                  <el-tag :type="getStatusType(item.status)">{{
                    getStatusText(item.status)
                  }}</el-tag>
                </div>
              </div>
              <div class="review-content">
                <div class="rating">
                  <el-rate v-model="item.rating" disabled />
                  <span class="rate-text">{{ rateTexts[item.rating - 1] }}</span>
                </div>
                <div class="comment" v-if="item.id !== editingId">
                  {{ item.comment }}
                </div>
                <div v-else class="edit-form">
                  <el-input
                    v-model="editForm.comment"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入评论内容"
                  />
                  <div class="edit-actions">
                    <el-button type="primary" size="small" @click="handleSave(item)"
                      >保存</el-button
                    >
                    <el-button size="small" @click="cancelEdit">取消</el-button>
                  </div>
                </div>
              </div>
              <div class="review-footer">
                <div class="likes">
                  <span class="like-count">
                    <i class="fas fa-thumbs-up"></i>
                    {{ item.likeCount || 0 }} 人点赞
                  </span>
                </div>
                <div class="actions">
                  <el-button
                    v-if="item.status !== 1"
                    type="primary"
                    link
                    @click="handleEdit(item)"
                  >
                    编辑
                  </el-button>
                  <el-button type="danger" link @click="handleDelete(item)">
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </template>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            prev-text="上一页"
            next-text="下一页"
            layout="prev, pager, next, total"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="咨询师评价" name="consultant">
        <!-- 咨询师评价查询条件 -->
        <div class="query-form">
          <el-form :model="consultantQueryForm" inline>
            <el-form-item label="状态">
              <el-select
                v-model="consultantQueryForm.status"
                placeholder="请选择状态"
                clearable
              >
                <el-option label="审核中" :value="0" />
                <el-option label="已通过" :value="1" />
                <el-option label="已拒绝" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="关键字">
              <el-input
                @keyup.enter="handleConsultantQuery"
                v-model="consultantQueryForm.keyword"
                placeholder="请输入评论内容关键字"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleConsultantQuery">查询</el-button>
              <el-button @click="resetConsultantQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 咨询师评价列表 -->
        <div class="review-list">
          <el-empty v-if="consultantReviewList.length === 0" description="暂无评论" />
          <template v-else>
            <div v-for="item in consultantReviewList" :key="item.id" class="review-item">
              <div class="review-header">
                <div class="course-info">
                  <el-avatar :src="item.avatar" />
                  <div class="info">
                    <div class="course-name">{{ item.consultantName }}</div>
                    <div class="review-time">{{ formatTime(item.reviewTime) }}</div>
                  </div>
                </div>
                <div class="review-status" style="display: flex; align-items: center">
                  <el-tooltip
                    v-if="item.status === 2"
                    :content="'拒绝原因:' + item.auditInfo"
                    placement="top"
                  >
                    <el-icon style="margin-right: 10px">
                      <InfoFilled />
                    </el-icon>
                  </el-tooltip>
                  <el-tag :type="getStatusType(item.status)">{{
                    getStatusText(item.status)
                  }}</el-tag>
                </div>
              </div>
              <div class="review-content">
                <div class="rating">
                  <MyRate :model-value="String(item.rating)" disabled />
                </div>
                <div class="comment" v-if="item.id !== consultantEditingId">
                  {{ item.comment }}
                </div>
                <div v-else class="edit-form">
                  <el-input
                    v-model="consultantEditForm.comment"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入评论内容"
                  />
                  <div class="edit-actions">
                    <el-button type="primary" size="small" @click="handleConsultantSave(item)"
                      >保存</el-button
                    >
                    <el-button size="small" @click="cancelConsultantEdit">取消</el-button>
                  </div>
                </div>
              </div>
              <div class="review-footer">
                <div class="actions">
                  <el-button
                    v-if="item.status !== 1"
                    type="primary"
                    link
                    @click="handleConsultantEdit(item)"
                  >
                    编辑
                  </el-button>
                  <el-button type="danger" link @click="handleConsultantDelete(item)">
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </template>
        </div>

        <!-- 咨询师评价分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="consultantPageNum"
            v-model:page-size="consultantPageSize"
            :total="consultantTotal"
            :page-sizes="[10, 20, 30, 50]"
            prev-text="上一页"
            next-text="下一页"
            layout="prev, pager, next, total"
            background
            @size-change="handleConsultantSizeChange"
            @current-change="handleConsultantCurrentChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { requestCoursePublishList, type CourseInfoVO } from "@/api/course";
import {
  deleteById,
  update,
  page,
  type CourseReview,
  type CourseReviewPageQuery,
} from "@/api/review";
import {
  getConsultantReviewPage,
  deleteConsultantReview,
  updateConsultantReview,
  type ConsultantReview
} from "@/api/consultantReviec";
import { rateTexts } from "@/constant/rateTexts";
import moment from "moment";
import { useUserStore } from "@/store/modules/user";
import MyRate from "@/components/MyRate.vue";

// Tab 激活状态
const activeTab = ref('course');

// 查询表单
const userStore = useUserStore();
const queryForm = ref({
  courseId: undefined as number | undefined,
  status: undefined as number | undefined,
  keyword: "",
});

// 咨询师查询表单
const consultantQueryForm = ref({
  consultantId: undefined as number | undefined,
  status: undefined as number | undefined,
  keyword: "",
});

// 分页参数
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 咨询师分页参数
const consultantPageNum = ref(1);
const consultantPageSize = ref(10);
const consultantTotal = ref(0);

// 数据列表
const reviewList = ref<CourseReview[]>([]);
const courseList = ref<CourseInfoVO[]>([]);
const consultantList = ref<any[]>([]); // TODO: 需要添加咨询师列表接口
const consultantReviewList = ref<ConsultantReview[]>([]);

// 编辑相关
const editingId = ref<number>();
const editForm = ref({
  comment: "",
});

// 咨询师评价编辑相关
const consultantEditingId = ref<number>();
const consultantEditForm = ref({
  comment: "",
});

// 获取课程列表
const getCourseList = async () => {
  try {
    const res = await requestCoursePublishList();
    courseList.value = res;
  } catch (error) {
    console.error("获取课程列表失败:", error);
  }
};

// 获取评论列表
const getReviewList = async () => {
  try {
    const params: Partial<CourseReviewPageQuery> = {
      ...queryForm.value,
      userId: userStore.userInfo?.userId,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    };
    const res = await page(params);
    reviewList.value = res.records;
    total.value = res.total;
  } catch (error) {
    console.error("获取评论列表失败:", error);
  }
};

// 查询
const handleQuery = () => {
  pageNum.value = 1;
  getReviewList();
};

// 重置
const resetQuery = () => {
  queryForm.value = {
    courseId: undefined,
    status: undefined,
    keyword: "",
  };
  handleQuery();
};

// 编辑评论
const handleEdit = (item: CourseReview) => {
  editingId.value = item.id;
  editForm.value.comment = item.comment;
};

// 取消编辑
const cancelEdit = () => {
  editingId.value = undefined;
  editForm.value.comment = "";
};

// 保存编辑
const handleSave = async (item: CourseReview) => {
  if (!editForm.value.comment.trim()) {
    ElMessage.warning("请输入评论内容");
    return;
  }

  try {
    const params: CourseReview = {
      ...item,
      comment: editForm.value.comment,
    };
    const res = await update(params);
    if (res) {
      ElMessage.success("修改成功");
      getReviewList();
      cancelEdit();
    }
  } catch (error) {
    console.error("修改评论失败:", error);
  }
};

// 删除评论
const handleDelete = async (item: CourseReview) => {
  try {
    await ElMessageBox.confirm("确定要删除这条评论吗？", "提示", {
      type: "warning",
    });
    const res = await deleteById(item.id);
    if (res) {
      ElMessage.success("删除成功");
      getReviewList();
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除评论失败:", error);
    }
  }
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getReviewList();
};

// 页码改变
const handleCurrentChange = (val: number) => {
  pageNum.value = val;
  getReviewList();
};

// 格式化时间
const formatTime = (time: string) => {
  return `发布时间：${moment(time).format("YYYY-MM-DD HH:mm:ss")}`;
};

// 获取状态类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0:
      return "warning";
    case 1:
      return "success";
    case 2:
      return "danger";
    default:
      return "info";
  }
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return "审核中";
    case 1:
      return "已通过";
    case 2:
      return "已拒绝";
    default:
      return "未知";
  }
};

// 咨询师评价相关方法
const getConsultantReviewList = async () => {
  try {
    const params = {
      ...consultantQueryForm.value,
      userId: userStore.userInfo?.userId,
      pageNum: consultantPageNum.value,
      pageSize: consultantPageSize.value,
    };
    const res = await getConsultantReviewPage(params);
    consultantReviewList.value = res.records;
    consultantTotal.value = res.total;
  } catch (error) {
    console.error("获取咨询师评价列表失败:", error);
  }
};

const handleConsultantQuery = () => {
  consultantPageNum.value = 1;
  getConsultantReviewList();
};

const resetConsultantQuery = () => {
  consultantQueryForm.value = {
    consultantId: undefined,
    status: undefined,
    keyword: "",
  };
  handleConsultantQuery();
};

const handleConsultantEdit = (item: ConsultantReview) => {
  consultantEditingId.value = item.id;
  consultantEditForm.value.comment = item.comment;
};

const cancelConsultantEdit = () => {
  consultantEditingId.value = undefined;
  consultantEditForm.value.comment = "";
};

const handleConsultantSave = async (item: ConsultantReview) => {
  if (!consultantEditForm.value.comment.trim()) {
    ElMessage.warning("请输入评论内容");
    return;
  }

  try {
    const params = {
      ...item,
      comment: consultantEditForm.value.comment,
    };
    const res = await updateConsultantReview(params);
    if (res) {
      ElMessage.success("修改成功");
      getConsultantReviewList();
      cancelConsultantEdit();
    }
  } catch (error) {
    console.error("修改咨询师评价失败:", error);
  }
};

const handleConsultantDelete = async (item: ConsultantReview) => {
  try {
    await ElMessageBox.confirm("确定要删除这条评论吗？", "提示", {
      type: "warning",
    });
    const res = await deleteConsultantReview(item.id);
    if (res) {
      ElMessage.success("删除成功");
      getConsultantReviewList();
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除咨询师评价失败:", error);
    }
  }
};

const handleConsultantSizeChange = (val: number) => {
  consultantPageSize.value = val;
  getConsultantReviewList();
};

const handleConsultantCurrentChange = (val: number) => {
  consultantPageNum.value = val;
  getConsultantReviewList();
};

// 评分文字映射
const getRateText = (rate: string) => {
  switch (rate) {
    case '1':
      return '不满意';
    case '2':
      return '一般';
    case '3':
      return '满意';
    default:
      return '';
  }
};

onMounted(() => {
  getCourseList();
  getReviewList();
  getConsultantReviewList();
});
</script>

<style scoped>
.my-review {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.query-form {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.review-list {
  margin-bottom: 20px;
}

.review-item {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.course-info {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.course-name {
  font-weight: 600;
  color: #333;
  font-size: 16px;
  text-align: left;
}

.review-time {
  color: #999;
  font-size: 13px;
  text-align: left;
}

.review-content {
  margin-bottom: 16px;
  text-align: left;
}

.rating {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.rate-text {
  color: #666;
  font-size: 14px;
}

.comment {
  color: #333;
  line-height: 1.8;
  font-size: 14px;
  text-align: left;
  white-space: pre-wrap;
  word-break: break-all;
}

.edit-form {
  margin-top: 12px;
}

.edit-actions {
  margin-top: 12px;
  text-align: right;
}

.review-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #eee;
}

.likes {
  color: #666;
  font-size: 14px;
}

.like-count {
  display: flex;
  align-items: center;
  gap: 6px;
}

.like-count i {
  color: #1890ff;
}

.actions {
  display: flex;
  gap: 12px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 16px;
}

:deep(.el-select) {
  width: 200px;
}

:deep(.el-input) {
  width: 200px;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-pagination .el-pagination__total) {
  margin-left: 16px;
}

@media (max-width: 768px) {
  .review-header {
    flex-direction: column;
    gap: 12px;
  }

  .review-status {
    align-self: flex-start;
  }

  :deep(.el-form--inline) {
    display: flex;
    flex-direction: column;
  }

  :deep(.el-form--inline .el-form-item) {
    margin-right: 0;
    margin-bottom: 16px;
  }

  :deep(.el-select),
  :deep(.el-input) {
    width: 100%;
  }
}
</style>
